import '../utils.dart';

/// 数据对象基类, 直接读写map
class DataBase {
  final Map data;
  DataBase(this.data);

  Object getItem(final String key) {
    if (data == null || key == null) return null;
    return data[key];
  }

  String getItemStr(final String key) {
    if (data == null || key == null) return "";
    return data[key];
  }

  int getItemInt(final String key) {
    if (data == null || key == null) return 0;
    Object v = data[key];
    if (v == null || v is int) return v;
    return Utils.strToInt("$v", 0);
  }

  DateTime getDateTime(final String key) {
    if (data == null || key == null) return null;
    Object v = data[key];
    if (v == null || v is DateTime) return v;
    return Utils.strToDateTime("$v", null);
  }

  double getFloat(final String key) {
    if (data == null || key == null) return 0.0;
    try {
      String v = data[key].toString();
      if (v == null || v.length == 0) return 0.0;
      return double.parse(v);
    } catch (e) {
      return 0.0;
    }
  }

  void setItem(final String key, Object v) {
    if (data == null || key == null) return;
    if (data.containsKey(key)) data.remove(key);
    data[key] = v;
  }

  void setDateTimeItem(final String key, DateTime v) {
    print(Utils.dateTimeToStr(v));
    data[key] = Utils.dateTimeToStr(v);
  }

  List<T> getList<T extends DataBase>(final String key, T callback(v)) {
    List<T> items = [];
    List<Map> _items = data[key];
    if (_items != null && callback != null) {
      _items.forEach((v) {
        items.add(callback(v));
      });
    }
    return items;
  }
}